package cn.geekyspace.scanhive.domain.service.impl;


import cn.geekyspace.scanhive.domain.entity.OperatorUserHistory;
import cn.geekyspace.scanhive.domain.mapper.OperatorUserHistoryMapper;
import cn.geekyspace.scanhive.domain.service.OperatorUserHistoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class OperatorUserHistoryServiceImpl implements OperatorUserHistoryService {

    private final OperatorUserHistoryMapper historyMapper;

    @Override
    public void saveOrUpdateHistory(String username) {
        if (username == null || username.isBlank()) {
            return;
        }
        historyMapper.insertOrUpdate(username);
    }

    @Override
    public void saveOrUpdateHistoryBatch(List<String> usernames) {
        if (usernames == null || usernames.isEmpty()) {
            return;
        }

        // 去掉 null、空字符串，去掉前后空格，并去重
        List<String> cleanList = usernames.stream()
                .filter(Objects::nonNull)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .distinct()
                .toList();

        if (cleanList.isEmpty()) {
            return;
        }

        historyMapper.insertOrUpdateBatch(cleanList);
    }

    @Override
    public List<OperatorUserHistory> getRecentHistory(int limit) {
        return historyMapper.selectList(
                new LambdaQueryWrapper<OperatorUserHistory>()
                        .orderByDesc(OperatorUserHistory::getLastAccessTime)
                        .last("LIMIT " + limit)
        );
    }



}
